import os
import uuid
import json
import time
import subprocess
import logging
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
import sqlite3
from datetime import datetime

# 配置
STREAM_CONFIG = {
    "K0123": "rtsp://localhost:8554/video",
    "K0124": "rtsp://localhost:8554/cam2",
    "K0125": "rtsp://localhost:8554/cam3"
}
FFMPEG_PATH = r"D:\devtools\rtsp\ffmpeg-n4.4.4-6-gd5fa6e3a91-win64-gpl-4.4\bin\ffmpeg"
VIDEO_STORAGE_PATH = "./videos"
DATABASE_PATH = "./events.db"
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# 确保目录存在
os.makedirs(VIDEO_STORAGE_PATH, exist_ok=True)


# 初始化数据库
def init_db():
    conn = sqlite3.connect(DATABASE_PATH)
    cursor = conn.cursor()
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS events (
        id TEXT PRIMARY KEY,
        stream_id TEXT NOT NULL,
        event_ts INTEGER NOT NULL,
        status TEXT NOT NULL DEFAULT 'PENDING',
        video_url TEXT,
        created_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
    )
    ''')
    conn.commit()
    conn.close()


init_db()


# 数据库工具函数
def get_db_connection():
    conn = sqlite3.connect(DATABASE_PATH)
    conn.row_factory = sqlite3.Row
    return conn


app = FastAPI()


def process_video(stream_id, event_ts, event_id):
    """处理视频截取的函数"""
    try:
        # 获取视频流地址
        stream_url = STREAM_CONFIG.get(stream_id)
        if not stream_url:
            raise ValueError(f"Stream ID {stream_id} not found")

        # 生成输出文件名
        output_filename = f"{event_id}.mp4"
        output_path = os.path.join(VIDEO_STORAGE_PATH, output_filename)

        # 计算截取时间（事件前后15秒）
        start_time = event_ts - 15
        duration = 30

        # 使用FFmpeg截取视频
        cmd = [
            FFMPEG_PATH, "-y",
            "-ss", str(start_time),
            "-i", stream_url,
            "-t", str(duration),
            "-c:v", "libx264",
            "-c:a", "aac",
            output_path
        ]

        # 执行FFmpeg命令
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        if result.returncode != 0:
            logger.error(f"FFmpeg error: {result.stderr}")
            raise RuntimeError(f"Video processing failed: {result.stderr}")

        # 生成视频URL
        video_url = f"http://localhost:8000/videos/{output_filename}"

        # 更新数据库状态
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE events SET status = ?, video_url = ?, updated_at = ? WHERE id = ?",
            ("COMPLETED", video_url, datetime.utcnow().isoformat(), event_id)
        )
        conn.commit()
        conn.close()

        logger.info(f"Video processed successfully: {video_url}")
        return video_url

    except Exception as e:
        logger.error(f"Error processing video: {str(e)}")
        # 更新数据库为失败状态
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE events SET status = ?, updated_at = ? WHERE id = ?",
            ("FAILED", datetime.utcnow().isoformat(), event_id)
        )
        conn.commit()
        conn.close()
        raise


@app.post("/event")
async def create_event(event_data: dict, background_tasks: BackgroundTasks):
    """创建事件并在后台处理视频"""
    # 验证输入
    if not event_data.get("stream_id") or "event_ts" not in event_data:
        raise HTTPException(status_code=400, detail="Missing required fields: stream_id and event_ts are required")

    stream_id = event_data["stream_id"]
    event_ts = event_data["event_ts"]

    # 验证stream_id
    if stream_id not in STREAM_CONFIG:
        raise HTTPException(status_code=404, detail=f"Stream ID {stream_id} not found")

    # 生成事件ID
    event_id = str(uuid.uuid4())
    now = datetime.utcnow().isoformat()

    # 保存到数据库
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "INSERT INTO events (id, stream_id, event_ts, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
        (event_id, stream_id, event_ts, "PENDING", now, now)
    )
    conn.commit()
    conn.close()

    # 添加到后台任务处理
    # background_tasks.add_task(process_video, stream_id, event_ts, event_id)

    return {
        "id": event_id,
        "stream_id": stream_id,
        "event_ts": event_ts,
        "status": "PENDING",
        "created_at": now,
        "updated_at": now
    }


@app.get("/event/{event_id}")
async def get_event(event_id: str):
    """查询事件状态"""
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM events WHERE id = ?", (event_id,))
    event = cursor.fetchone()
    conn.close()

    if not event:
        raise HTTPException(status_code=404, detail="Event not found")

    return dict(event)


@app.get("/videos/{filename}")
async def get_video(filename: str):
    """提供视频文件访问"""
    file_path = os.path.join(VIDEO_STORAGE_PATH, filename)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="Video not found")

    from fastapi.responses import FileResponse
    return FileResponse(file_path)


@app.get("/health")
async def health_check():
    return {"status": "ok"}
